<?php
namespace App\Http\Controllers\ConsoleWeb;

use App\Http\Controllers\Business\Shop\V1\Salesman\SalesmanManagement;
use App\Http\Controllers\WebController;
use App\Http\Controllers\Business\Admin\Shop\ShopManagement;
use App\Http\Controllers\Business\Admin\Shop\QrcodeManagement;
use App\Http\Controllers\Business\Admin\Salesman\ShopSalesmanManagement;
use App\Http\Controllers\Business\Admin\Common\Common;
use App\Http\Controllers\Business\Admin\Auth\AdminAuth;
use App\Http\Controllers\Business\Admin\Area\AreaManagement;
use App\Http\Controllers\Business\Admin\Log\ShopLog;
use App\Models\City;
use App\Models\Shop;
use App\Models\AdminUser;
use App\Models\ShopUser;
use App\Models\ShopEvent;
use App\Models\Oss;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\Auth;
use Maatwebsite\Excel\Facades\Excel;
use Log;

class ShopController extends WebController
{
    //商家列表
    public function shopList() {
        $cityId = $this->request->get('cityid');
        $startTime = '';
        $lastTime = '';
        $firstClassId = '%';
        $secondClassId = '%';
        $isDouble = '%';
        $search = '%';
        $perpage = 10000;

        $result = ShopManagement::shopManagement($cityId,$startTime,$lastTime,$firstClassId,$secondClassId,$isDouble,$search,$perpage);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId
        ];
        return view('console.shop.shop_list', $data);
    }
    //商家详情
    public function getShop() {
        $shopId = $this->request->get('shopid');
        $cityId = $this->request->get('cityid');
        $shopResult = ShopManagement::shopDetails($shopId, $cityId);
        if($shopResult['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $shopResult['data'];
        $data['cityid'] = $cityId;
        $shopContractResult = ShopManagement::getShopContract($shopId);
        if($shopContractResult['status'] == 'success') {
            $shopContract = $shopContractResult['data'];
            $data['contractstarttime'] = $shopContract['starttime'];
            $data['contractendtime'] = $shopContract['lasttime'];
            $data['contractorid'] = $shopContract['contractorid'];
        } else {
            $data['contractstarttime'] = '';
            $data['contractendtime'] = '';
            $data['contractorid'] = '';
        }
        //开拓人修改逻辑
//        if($data['contractorid']) {
//            $contractor = AdminAuth::getUserNameAndMobileByUserId($data['contractorid']) ;
//            $data['contractorname'] = isset($contractor['data']['realname']) ? $contractor['data']['realname'] : '';
//            $data['contractormobile'] = isset($contractor['data']['mobile']) ? $contractor['data']['mobile'] : '';
//        } else {
//            $data['contractorname'] = '';
//            $data['contractormobile'] = '';
//        }
        if($data['oldid']){
            $oldMaintainer = AdminAuth::getUserNameAndMobileByUserId($data['oldid']) ;
            $data['oldmaintainername'] = isset($oldMaintainer['data']['realname']) ? $oldMaintainer['data']['realname'] : '';
            $data['oldmaintainermobile'] = isset($oldMaintainer['data']['mobile']) ? $oldMaintainer['data']['mobile'] : '';
        }else{
            $data['oldmaintainername'] = '';
            $data['oldmaintainermobile'] = '';
        }
        if(isset($data['maintainerid'])) {
            $maintainer = AdminAuth::getUserNameAndMobileByUserId($data['maintainerid']) ;
            $data['maintainername'] = isset($maintainer['data']['realname']) ? $maintainer['data']['realname'] : '';
            $data['maintainermobile'] = isset($maintainer['data']['mobile']) ? $maintainer['data']['mobile'] : '';
        } else {
            $data['maintainername'] = '';
            $data['maintainermobile'] = '';
        }
        $shopReviewResult = ShopManagement::getShopReviewByShopId($shopId, $cityId);
        if($shopReviewResult['status'] == 'success') {
            $shopReview = $shopReviewResult['data'];
            $data['firstverifynote'] = $shopReview['firstverifynote'];
            $data['firstverifyid'] = $shopReview['firstverifyid'];
            $firstverify = AdminAuth::getUserNameAndMobileByUserId($data['firstverifyid']) ;
            $data['firstverifyname'] = isset($firstverify['data']['realname']) ? $firstverify['data']['realname'] : '';
            $data['firstverifymobile'] = isset($firstverify['data']['mobile']) ? $firstverify['data']['mobile'] : '';
            $data['firstverifytime'] = $shopReview['firstverifytime'];
            $data['lastverifynote'] = $shopReview['lastverifynote'];
            $data['lastverifyid'] = $shopReview['lastverifyid'];
            $lastverify = AdminAuth::getUserNameAndMobileByUserId($data['lastverifyid']) ;
            $data['lastverifyname'] = isset($lastverify['data']['realname']) ? $lastverify['data']['realname'] : '';
            $data['lastverifymobile'] = isset($lastverify['data']['mobile']) ? $lastverify['data']['mobile'] : '';
            $data['lastverifytime'] = $shopReview['lastverifytime'];
        } else {
            $data['firstverifynote'] = '';
            $data['firstverifyid'] = '';
            $data['firstverifyname'] = '';
            $data['firstverifymobile'] = '';
            $data['firstverifytime'] = '';
            $data['lastverifynote'] = '';
            $data['lastverifyid'] = '';
            $data['lastverifyname'] = '';
            $data['lastverifymobile'] = '';
            $data['lastverifytime'] = '';
        }
        $photos = json_decode($data['photos'], true);
        $goodsPhotos = json_decode($data['goodsphotos'], true);
        $data['photos'] = $photos;
        $data['goodsphotos'] = $goodsPhotos;
        $shopEventResult = ShopManagement::getShopEvent($shopId);
        if($shopEventResult['status'] == 'failed') {
            $data['shopevent'] = '';
        } else {
            $shopEvent = $shopEventResult['data'];
            $shopEventString = '';
            foreach($shopEvent as $list) {
                $shopEventString .= date('Y-m-d', strtotime($list['event'])) . ',';
            }
            $data['shopevent'] = rtrim($shopEventString,',');
        }

        $data['photodomain'] = env('IMAGE_DOMAIN');
        return view('console.shop.shop_details', $data);
    }
    //新增/修改消息内容
    public function bigPicture() {
        $currenturl = $this->request->get('currenturl');
        $content = $this->request->get('content');
        $count = $this->request->get('count');
        $data = [
            'currenturl' => $currenturl,
            'content'=>$content,
            'count' => $count
        ];
        return view('console.shop.big_picture', $data);
    }
    //新增商家
    public function newShop() {
        $cityId = $this->request->get('cityid');
        $data = Oss::getStsAuth();
        $adminUserId = Auth::guard('adminweb')->id();
        $data['adminUserId'] = $adminUserId;
        $data['cityid'] = $cityId;
        //判断添加商家的是商务人员还是客户和后台人员并返回结果
        $businessPersonnel = ShopManagement::getBusinessPersonnel($cityId);
        $data['businessPersonnel'] = $businessPersonnel['data'];
        $areaInfo = AreaManagement::getProvinceAndCityByCityId($cityId);
        if($areaInfo['status'] == 'failed') {
            return view('errors.404');
        }
        $data['cityname'] = $areaInfo['data']['cityname'];
        $data['provinceid'] = $areaInfo['data']['provinceid'];
        $data['provincename'] = $areaInfo['data']['provincename'];
        $data['districtlists'] = $areaInfo['data']['districtlists'];
        return view('console.shop.new_shop', $data);
    }
    //提交新增商家数据, 数据写入到shop_reviews表中
    public function addShop() {
        //$adminUserId = Auth::guard('adminweb')->id();
        $input = $this->request->input();
        $other = $input['other'];
        $tips = $input['tips'];
        $consumerInfo = json_encode([
            'other' => $other,
            'tips' => $tips
        ]);
        //获取商务人员的ID
        $adminUserId = $input['maintainerid'];

        $shopUserName = trim($input['parentname']);
        $shopUserMobile = trim($input['parentmobile']);
        $auth = [];
        $addShopUser = ShopManagement::addShopUser($shopUserName, $shopUserMobile, $auth);
        $logo = $input['logo'];
        $photosPath = $input['photospath'];
        $photosCount = $input['photoscount'];
        $photosArray = [];
        if($photosCount>1) {
            for($i=0; $i<$photosCount; $i++) {
                array_push($photosArray, $photosPath."_".$i);
            }
        } elseif($photosCount == 1) {
            array_push($photosArray, $photosPath."_0");
        }
        $photos = json_encode($photosArray);
        $goods = $input['goods'];
        $bankCardPhoto = $input['bankcardphoto'];
        $licensePhoto = $input['licensephoto'];
        $idCardFrontPhoto = $input['idcardfrontphoto'];
        $idCardBackPhoto = $input['idcardbackphoto'];
        $data = [
            'code' => trim($input['code']),
            'name' => trim($input['name']),
            'logo' => $logo,
            'firstclassid'=> $input['firstclassid'],
            'secondclassid' => $input['secondclassid'],
            'firstclassname' => $input['firstclassname'],
            'secondclassname' => $input['secondclassname'],
            'label' => $input['label'],
            'maxsales' => $input['maxsales'],
            'provinceid' => $input['shopprovinceid'],
            'cityid' => $input['shopcityid'],
            'districtid' => $input['shopdistrictid'],
            'businessareaid' => $input['shopbusinessareaid'],
            'cityname' => $input['shopcityname'],
            'districtname' => $input['shopdistrictname'],
            'businessareaname' => $input['shopbusinessareaname'],
            'longitude' => $input['longitude'],
            'latitude' => $input['latitude'],
            'address' => $input['address'],
            'photos' => $photos,
            'goodsphotos' => $goods,
            'consumerinfo' => $consumerInfo,
            'invoice' => $input['invoice'],
            'content' => $input['other'],
            'notpartakegoods' => $input['notpartakegoods'],
            'description' => $input['description'],
            'contactnumber' => trim($input['contactnumber']),
            'smsphone' => trim($input['smsphone']),
            'businesshours' => $input['businesshours'],
            'buynumber' => $input['buynumber'],
            'weekdoubleday' => $input['weekdoubleday'],
            'maintainerid' => $adminUserId,
            'parentmobile' => trim($input['parentmobile']),
            'parentname' => trim($input['parentname']),
            'childmobile' => '',
            'event' => $input['event'],
            'note' => '',
            'status' => '1',
            'shopuserid' => '',
            'idcard' => $input['idcard'],
            'bankname' => $input['bankname'],
            'cardholder' => $input['cardholder'],
            'bankcard' => $input['bankcard'],
            'opencardbank' => $input['opencardbank'],
            'bankprovince' => $input['bankprovince'],
            'bankcity' => $input['bankcity'],
            'contractstarttime' => $input['contractstarttime'],
            'contractendtime' => $input['contractendtime'],
            'bankcardphoto' => $bankCardPhoto,
            'licensephoto' => $licensePhoto,
            'idcardfrontphoto' => $idCardFrontPhoto,
            'idcardbackphoto' => $idCardBackPhoto,
            'firstverifynote' => '新增商家',
            'firstverifyid' => $adminUserId,
            'firstverifytime' => date('Y-m-d H:i:s'),
            'lastverifynote' => '',
            'lastverifyid' => '',
            'eventremark'=>$input['remark'],

        ];
        $result = ShopManagement::addShopReview($data);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            //return redirect()->to('/console/shop/list?cityid=124');
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //批量生成二维码
    public function batchQrCode() {
        $cityId = $this->request->get('cityid');
        if($this->request->has('count')) {
            $count = $this->request->get('count');
        } else {
            $count = 50;
        }
        $result = QrcodeManagement::batchShopQrcode($cityId, $count);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $fileName = $result['data'];
        return response()->download($fileName)->deleteFileAfterSend(true);;
    }
    //绑定二维码
    public function bindingQrCode() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $qrCode = $this->request->get('qrcode');
        $result = QrcodeManagement::bindingShopQrcode($cityId, $shopId, $qrCode);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //商家修改页面
    public function shopCheck() {
        $data = Oss::getStsAuth();
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $type = $this->request->get('type'); //type 包含基本信息basic，商家相册photo，翻倍日doublecalendar，代付规则(payrules)，收款帐号payaccount，法人信息legalperson，经营资质qualification
        $result = ShopManagement::shopDetails($shopId, $cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $shopDetail = $result['data'];
        if(isset($shopDetail['goodsphotos'])) {
            $shopDetail['goodsphotos'] = json_decode($shopDetail['goodsphotos'], true);
        }
        if(isset($shopDetail['photos'])) {
            $shopDetail['photos'] = json_decode($shopDetail['photos'], true);
        }
        $shopEventResult = ShopManagement::getShopEvent($shopId);
        if($shopEventResult['status'] == 'failed') {
            $data['shopevent'] = '';
        } else {
            $shopEvent = $shopEventResult['data'];
            $shopEventString = '';
            foreach($shopEvent as $list) {
                $shopEventString .= date('Y-m-d', strtotime($list['event'])) . ',';
            }
            $shopEventString = rtrim($shopEventString, ',');
            $data['shopevent'] = $shopEventString;
        }
        $provinceId = isset($shopDetail['provinceid']) ? $shopDetail['provinceid'] : 1;
        $cityResult = Common::getCityByProvinceId($provinceId);
        $cityArray = $cityResult['data'];
        $data['provinceid'] = $provinceId;
        $data['cityid'] = $cityId;
        $data['type'] = $type;
        $data['data'] = $shopDetail;
        $data['cityarray'] = $cityArray;
        $data['shopid'] = $shopId;
        $adminUserId = Auth::guard('adminweb')->id();
        $data['adminUserId'] = $adminUserId;
        $data['photodomain'] = 'http://file.fbw-china.com/';
        $contractTimeResult = ShopManagement::getLastContract($shopId);
        if($contractTimeResult['status'] == 'failed') {
            $data['contractstarttime'] = '';
            $data['contractendtime'] = '';
        } else {
            $data['contractstarttime'] = $contractTimeResult['data']['starttime'];
            $data['contractendtime'] = $contractTimeResult['data']['lasttime'];
        }
        $data['content'] = isset($shopDetail['content']) && !empty($shopDetail['content'])?str_replace(array("\r\n", "\r", "\n"), "", $shopDetail['content']):'';
        return view('console.shop.shop_check', $data);
    }
    //删除商家
    public function deleteShop() {
        $shopId = $this->request->get('shopid');
        $notes =  $this->request->get('notes');
        $cityId = $this->request->get('cityid');
        $type = '0';
        $result = ShopManagement::shopStatusEdit($shopId, $type);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            //$result = ShopManagement::shopDetails($shopId, $cityId); //TODO 下架理由
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //商家下架
    public function downShelfShop() {
        $shopId = $this->request->get('shopid');
        $deductionNote = $this->request->get('deductionnote');
        $deductionType = $this->request->get('deductiontype');
        $note = $this->request->get('note');
        $cityId = $this->request->get('cityid');
        $type = '0';
        $result = ShopManagement::shopStatusEdit($shopId, $type, $deductionType);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            ShopLog::writeShopLog($shopId, 'downshelf', $deductionType, $note, $deductionNote);
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //商家上架
    public function upShelfShop() {
        $shopId = $this->request->get('shopid');
        $notes =  $this->request->get('notes');
        $cityId = $this->request->get('cityid');
        $type = '1';
        $result = ShopManagement::shopStatusEdit($shopId, $type);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            ShopLog::writeShopLog($shopId, 'upshelf', 0, '商家上架','');
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //商家续签
    public function renewShop() {
        $shopId = $this->request->get('shopid');
        $cityId = $this->request->get('cityid');
        $contractorId = $this->request->get('contractorid');
        $startTime = $this->request->get('starttime');
        $endTime = $this->request->get('endtime');
        $result = ShopManagement::renewShop($shopId, $contractorId,$startTime, $endTime);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            $shopName = Shop::where('id',$shopId)->pluck('name')->first();
            $realname = AdminUser::where('id',$contractorId)->pluck('realname')->first();
            $reason = '增加商家续约（续约人:"'.$realname.'";续约商家:"'.$shopName.'";开始日期:"'.$startTime.'";终止日期:"'.$endTime.'"）';
            $shopLog = ShopLog::writeShopLog($shopId,'update_shop_contract',0,$reason,'');
            if($cityId == 1) {
                //默认给南昌开放商家地推
                $addShopSalesman = ShopSalesmanManagement::addShopSalesman($shopId, $cityId, 'common');
            }
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //提交商家修改信息
    public function editShop() {
        $input = $this->request->input();
        $type = $input['type'];
        $shopId = $input['shopid'];
        //$fileDomain = 'http://file.fbw-china.com/';
        //type 包含基本信息basic，商家相册photo，翻倍日doublecalendar，代付规则(payrules)，收款帐号payaccount，法人信息legalperson，经营资质qualification
        //获取商家信息
        $shopInfo = Shop::where('id',$shopId)->first();
        $event = '';
        $shopEvent = [];
        if($type == 'basic') {
            $data = [
                'name' => $input['name'],
                'code' => $input['code'],
                'contactnumber' => $input['contactnumber'],
                'businesshours' => $input['businesshours'],
                'smsphone' => $input['smsphone'],
                'provinceid' => $input['shopprovinceid'],
                'cityid' => $input['shopcityid'],
                'cityname' => $input['shopcityname'],
                'districtid' => $input['shopdistrictid'],
                'districtname' => $input['shopdistrictname'],
                'businessareaid' => $input['shopbusinessareaid'],
                'businessareaname' => $input['shopbusinessareaname'],
                'address' => $input['address'],
                'longitude' => $input['longitude'],
                'latitude' => $input['latitude'],
                'firstclassid' => $input['firstclassid'],
                'firstclassname' => $input['firstclassname'],
                'secondclassid' => $input['secondclassid'],
                'secondclassname' => $input['secondclassname'],
                'label' => $input['label'],
                'description' => $input['description'],
            ];
        } elseif($type == 'photo') {
            $logo = $input['logo'];
            $oldPhotos = $input['oldphotos'];
            $photosPath = $input['photospath'];
            $photosCount = $input['photoscount'];
            $goods = $input['goods'];
            if($oldPhotos != '') {
                $photosArray = explode(',', $oldPhotos);
                if(!is_array($photosArray)) {
                    $photosArray = [];
                }
            } else {
                $photosArray = [];
            }
            if($photosCount>1) {
                for($i=0; $i<$photosCount; $i++) {
                    array_push($photosArray, $photosPath."_".$i);
                }
            } elseif($photosCount == 1) {
                array_push($photosArray, $photosPath."_0");
            }
            //迁移步骤
            $newLogo = "upload/shop/" . $shopId."/logo".time();
            $newLogo = (ShopManagement::migrationSingleFile($logo, $newLogo)) ? $newLogo: $logo;

            $photos = json_encode($photosArray);
            $newPhotos = ShopManagement::migrationPhotos($shopId, $photos);
            $newPhotos = ($newPhotos != '') ? $newPhotos: $photos;

            $newGoodsPhotos = ShopManagement::migrationGoodsPhotos($shopId, $goods);
            $newGoodsPhotos = ($newGoodsPhotos != '') ? $newGoodsPhotos : $goods;
            $data = [
                'logo' => $newLogo,
                'photos' => $newPhotos,
                'goodsphotos'=> $newGoodsPhotos,
            ];
        } elseif($type == 'doublecalendar') {
            $shopEvent = ShopEvent::where('shopid',$shopId)->select('event')->get();
            $event = $input['event'];
            $eventremark = $input['remark'];
            $addEvent = ShopManagement::addShopEvent($shopId, $event);
            $data = [
                'weekdoubleday' => $input['weekdoubleday'],
                'eventremark'=>$eventremark,
            ];
        } elseif($type == 'payrules') {
            $data = [
                'buynumber' => $input['buynumber'],
                'maxsales' => $input['maxsales'],
                'notpartakegoods' => $input['notpartakegoods'],
                'invoice' => $input['invoice'],
                'content' => $input['content'],
            ];
        } elseif($type == 'payaccount') {
            $data = [
                'cardholder' => $input['cardholder'],
                'bankcard' => $input['bankcard'],
                'bankname' => $input['bankname'],
                'bankprovince' => $input['bankprovince'],
                'bankcity' => $input['bankcity'],
                'opencardbank' => $input['opencardbank'],
            ];
        } elseif($type == 'legalperson') {
            $data = [
                'parentname' => $input['parentname'],
                'parentmobile' => $input['parentmobile'],
                //'idcard' => $input['idcard']//去掉修改银行卡号
            ];
        } elseif($type == 'qualification') {
            $data = [
                'bankcardphoto'=>$input['bankcardphoto'],
                'licensephoto'=>$input['licensephoto'],
                'idcardfrontphoto'=>$input['idcardfrontphoto'],
                'idcardbackphoto'=>$input['idcardbackphoto']
            ];
        } else {
            return $this->responseError("类型错误");
        }
        $result = ShopManagement::editShop($shopId, $data);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            $updateShopLog = ShopLog::writeLogAfterShopInfoUpdated($shopId,$type,$data,$shopInfo,$event,$shopEvent);
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //修改商家帐号
    public function updateShopParentMobile() {
        $type = $this->request->get('type');
        $shopId = $this->request->get('shopid');
        $oldParentMobile = $this->request->get('oldparentmobile');
        $newParentMobile = $this->request->get('newparentmobile');
        if($type == 'shop') {
            $result = ShopManagement::shopAdminUserEdit($shopId, $oldParentMobile, $newParentMobile);
        } elseif($type == 'shop_review') {
            $result = ShopManagement::updateShopParentMobile($shopId, $oldParentMobile, $newParentMobile, $type);
        } else {
            return $this->responseError("类型错误");
        }
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //商务待处理列表
    public function shopWaitList() {
        $cityId = $this->request->get('cityid');
        $startTime = '';
        $lastTime = '';
        $search = '%';
        $result = ShopManagement::staffVerifyManagement($cityId, $startTime, $lastTime, $search);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId
        ];
        return view('console.shop.shop_waitlist', $data);
    }
    //客服待处理列表
    public function customWaitList() {
        $cityId = $this->request->get('cityid');
        $startTime = '';
        $lastTime = '';
        $search = '';
        $result = ShopManagement::verifyManagement($cityId, $startTime, $lastTime, $search);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId
        ];
        return view('console.shop.custom_waitlist', $data);
    }
    //商务，客服等待审核详情页面
    public function getShopReview() {
        $shopReviewId = $this->request->get('shopreviewid');
        $cityId = $this->request->get('cityid');
        $adminRole = $this->request->get('adminrole');
        $result = ShopManagement::shopReviewDetails($shopReviewId, $cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        if(isset($data['maintainerid'])) {
            $maintainer = AdminAuth::getUserNameAndMobileByUserId($data['maintainerid']) ;
            $data['maintainername'] = isset($maintainer['data']['realname']) ? $maintainer['data']['realname'] : '';
            $data['maintainermobile'] = isset($maintainer['data']['mobile']) ? $maintainer['data']['mobile'] : '';
        } else {
            $data['maintainername'] = '';
            $data['maintainermobile'] = '';
        }
        if(isset($data['shopid']) && ($data['shopid'] != 0)) {
            $shopContractResult = ShopManagement::getShopContract($data['shopid']);
            if($shopContractResult['status'] == 'success') {
                $contractorId = $shopContractResult['data']['id'];
                $contractor = AdminAuth::getUserNameAndMobileByUserId($contractorId);
                $data['contractorname'] = isset($contractor['data']['realname']) ? $contractor['data']['realname'] : '';
                $data['contractormobile'] = isset($contractor['data']['mobile']) ? $contractor['data']['mobile'] : '';
            } else {
                $data['contractorname'] = $data['maintainername'];
                $data['contractormobile'] = $data['maintainermobile'];
            }
        } else {
            $data['contractorname'] = $data['maintainername'];
            $data['contractormobile'] = $data['maintainermobile'];
        }
        if(isset($data['firstverifyid'])) {
            $firstverify = AdminAuth::getUserNameAndMobileByUserId($data['firstverifyid']) ;
            $data['firstverifyname'] = isset($firstverify['data']['realname']) ? $firstverify['data']['realname'] : '';
            $data['firstverifymobile'] = isset($firstverify['data']['mobile']) ? $firstverify['data']['mobile'] : '';
        } else {
            $data['firstverifyname'] = '';
            $data['firstverifymobile'] = '';
        }
        if(isset($data['lastverifyid'])) {
            $lastverify = AdminAuth::getUserNameAndMobileByUserId($data['lastverifyid']) ;
            $data['lastverifyname'] = isset($lastverify['data']['realname']) ? $lastverify['data']['realname'] : '';
            $data['lastverifymobile'] = isset($lastverify['data']['mobile']) ? $lastverify['data']['mobile'] : '';
        } else {
            $data['lastverifyname'] = '';
            $data['lastverifymobile'] = '';
        }
        $photos = json_decode($data['photos'], true);
        $goodsPhotos = json_decode($data['goodsphotos'], true);
        $data['photos'] = is_array($photos)? $photos: [];
        $data['goodsphotos'] = is_array($goodsPhotos)?$goodsPhotos:[];
        $data['adminrole'] = $adminRole;
        $data['cityid'] = $cityId;
        //判断添加商家的是商务人员还是客户和后台人员并返回结果
        $businessPersonnel = ShopManagement::getBusinessPersonnel($cityId);
        $data['businessPersonnel'] = $businessPersonnel['data'];
        return view('console.shop.shop_review', $data);
    }
    //商务，客服等待审核修改页面
    public function shopReviewCheck() {
        $data = Oss::getStsAuth();
        $cityId = $this->request->get('cityid');
        $shopReviewId = $this->request->get('shopreviewid');
        $adminRole = $this->request->get('adminrole');
        $type = $this->request->get('type'); //type 包含基本信息basic，商家相册photo，翻倍日doublecalendar，代付规则(payrules)，收款帐号payaccount，法人信息legalperson，经营资质qualification
        $result = ShopManagement::shopReviewDetails($shopReviewId, $cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $shopDetail = $result['data'];
        if(isset($shopDetail['goodsphotos'])) {
            $shopDetail['goodsphotos'] = json_decode($shopDetail['goodsphotos'], true);
        }
        if(isset($shopDetail['photos'])) {
            $shopDetail['photos'] = json_decode($shopDetail['photos'], true);
        }
        $provinceId = isset($shopDetail['provinceid']) ? $shopDetail['provinceid'] : 1;
        $cityResult = Common::getCityByProvinceId($provinceId);
        $cityArray = $cityResult['data'];
        $data['cityid'] = $cityId;
        $data['provinceid'] = $provinceId;
        $data['type'] = $type;
        $data['data'] = $shopDetail;
        $data['cityarray'] = $cityArray;
        $data['shopreviewid'] = $shopReviewId;
        $adminUserId = Auth::guard('adminweb')->id();
        $data['adminUserId'] = $adminUserId;
        $data['adminrole'] = $adminRole;
        return view('console.shop.shop_review_check', $data);
    }
    //修改商务待处理中的商家详情
    public function editBusinessPeopleShopReview() {
        $input = $this->request->input();
        $type = $input['type'];
        $shopReviewId = $input['shopreviewid'];
        //type 包含基本信息basic，商家相册photo，翻倍日doublecalendar，代付规则(payrules)，收款帐号payaccount，法人信息legalperson，经营资质qualification
        if($type == 'basic') {
            $data = [
                'name' => $input['name'],
                'code' => $input['code'],
                'contactnumber' => $input['contactnumber'],
                'businesshours' => $input['businesshours'],
                'smsphone' => $input['smsphone'],
                'provinceid' => $input['shopprovinceid'],
                'cityid' => $input['shopcityid'],
                'cityname' => $input['shopcityname'],
                'districtid' => $input['shopdistrictid'],
                'districtname' => $input['shopdistrictname'],
                'businessareaid' => $input['shopbusinessareaid'],
                'businessareaname' => $input['shopbusinessareaname'],
                'address' => $input['address'],
                'longitude' => $input['longitude'],
                'latitude' => $input['latitude'],
                'firstclassid' => $input['firstclassid'],
                'firstclassname' => $input['firstclassname'],
                'secondclassid' => $input['secondclassid'],
                'secondclassname' => $input['secondclassname'],
                'label' => $input['label'],
                'description' => $input['description'],
            ];
        } elseif($type == 'photo') {
            $logo = $input['logo'];
            $oldPhotos = $input['oldphotos'];
            $photosPath = $input['photospath'];
            $photosCount = $input['photoscount'];
            $goods = $input['goods'];
            if($oldPhotos != '') {
                $photosArray = explode(',', $oldPhotos);
                if(!is_array($photosArray)) {
                    $photosArray = [];
                }
            } else {
                $photosArray = [];
            }
            if($photosCount>1) {
                for($i=0; $i<$photosCount; $i++) {
                    array_push($photosArray, $photosPath."_".$i);
                }
            } elseif($photosCount == 1) {
                array_push($photosArray, $photosPath."_0");
            }
            //迁移步骤
            $data = [
                'logo' => $logo,
                'photos' => json_encode($photosArray),
                'goodsphotos'=> $goods,
            ];
        } elseif($type == 'doublecalendar') {
            $data = [
                'event' => $input['event'],
                'weekdoubleday' => $input['weekdoubleday'],
                'eventremark'=>$input['remark'],
            ];
        } elseif($type == 'payrules') {
            $data = [
                'buynumber' => $input['buynumber'],
                'maxsales' => $input['maxsales'],
                'notpartakegoods' => $input['notpartakegoods'],
                'invoice' => $input['invoice'],
                'content' => $input['content'],
            ];
        } elseif($type == 'payaccount') {
            $data = [
                'cardholder' => $input['cardholder'],
                'bankcard' => $input['bankcard'],
                'bankname' => $input['bankname'],
                'bankprovince' => $input['bankprovince'],
                'bankcity' => $input['bankcity'],
                'opencardbank' => $input['opencardbank'],
                'idcard' => $input['idcard'],
            ];
        } elseif($type == 'legalperson') {
            $data = [
                'parentname' => $input['parentname'],
                'parentmobile' => $input['parentmobile'],
                //'idcard' => $input['idcard'],
                'contractstarttime' => $input['contractstarttime'],
                'contractendtime' => $input['contractendtime'],
            ];
        } elseif($type == 'qualification') {
            $data = [
                'bankcardphoto'=>$input['bankcardphoto'],
                'licensephoto'=>$input['licensephoto'],
                'idcardfrontphoto'=>$input['idcardfrontphoto'],
                'idcardbackphoto'=>$input['idcardbackphoto']
            ];
        } else {
            return $this->responseError("类型错误");
        }
        $result = ShopManagement::editShopReview($shopReviewId, $data);
        return $this->responseSuccessMessage($result['message']);
    }
    //修改客服待处理中的商家详情
    public function editCustomerShopReview() {
        $input = $this->request->input();
        $type = $input['type'];
        $shopReviewId = $input['shopreviewid'];
        //type 包含基本信息basic，商家相册photo，翻倍日doublecalendar，代付规则(payrules)，收款帐号payaccount，法人信息legalperson，经营资质qualification
        if($type == 'basic') {
            $data = [
                'name' => $input['name'],
                'code' => $input['code'],
                'contactnumber' => $input['contactnumber'],
                'businesshours' => $input['businesshours'],
                'smsphone' => $input['smsphone'],
                'provinceid' => $input['shopprovinceid'],
                'cityid' => $input['shopcityid'],
                'cityname' => $input['shopcityname'],
                'districtid' => $input['shopdistrictid'],
                'districtname' => $input['shopdistrictname'],
                'businessareaid' => $input['shopbusinessareaid'],
                'businessareaname' => $input['shopbusinessareaname'],
                'address' => $input['address'],
                'longitude' => $input['longitude'],
                'latitude' => $input['latitude'],
                'firstclassid' => $input['firstclassid'],
                'firstclassname' => $input['firstclassname'],
                'secondclassid' => $input['secondclassid'],
                'secondclassname' => $input['secondclassname'],
                'label' => $input['label'],
                'description' => $input['description'],
            ];
        } elseif($type == 'photo') {
            $logo = $input['logo'];
            $oldPhotos = $input['oldphotos'];
            $photosPath = $input['photospath'];
            $photosCount = $input['photoscount'];
            $goods = $input['goods'];
            if($oldPhotos != '') {
                $photosArray = explode(',', $oldPhotos);
                if(!is_array($photosArray)) {
                    $photosArray = [];
                }
            } else {
                $photosArray = [];
            }
            if($photosCount>1) {
                for($i=0; $i<$photosCount; $i++) {
                    array_push($photosArray, $photosPath."_".$i);
                }
            } elseif($photosCount == 1) {
                array_push($photosArray, $photosPath."_0");
            }
            //迁移步骤
            $data = [
                'logo' => $logo,
                'photos' => json_encode($photosArray),
                'goodsphotos'=> $goods,
            ];
        } elseif($type == 'doublecalendar') {
            $data = [
                'event' => $input['event'],
                'weekdoubleday' => $input['weekdoubleday'],
                'eventremark'=>$input['remark'],
            ];
        } elseif($type == 'payrules') {
            $data = [
                'buynumber' => $input['buynumber'],
                'maxsales' => $input['maxsales'],
                'notpartakegoods' => $input['notpartakegoods'],
                'invoice' => $input['invoice'],
                'content' => $input['content'],
            ];
        } elseif($type == 'payaccount') {
            $data = [
                'cardholder' => $input['cardholder'],
                'bankcard' => $input['bankcard'],
                'bankname' => $input['bankname'],
                'bankprovince' => $input['bankprovince'],
                'bankcity' => $input['bankcity'],
                'opencardbank' => $input['opencardbank'],
                'idcard' => $input['idcard']
            ];
        } elseif($type == 'legalperson') {
            $data = [
                'parentname' => $input['parentname'],
                'parentmobile' => $input['parentmobile'],
                //'idcard' => $input['idcard']
                'contractstarttime' => $input['contractstarttime'],
                'contractendtime' => $input['contractendtime'],
            ];
        } elseif($type == 'qualification') {
            $data = [
                'bankcardphoto'=>$input['bankcardphoto'],
                'licensephoto'=>$input['licensephoto'],
                'idcardfrontphoto'=>$input['idcardfrontphoto'],
                'idcardbackphoto'=>$input['idcardbackphoto'],
            ];
        } else {
            return $this->responseError("类型错误");
        }
        $result = ShopManagement::editShopReview($shopReviewId, $data);
        return $this->responseSuccessMessage($result['message']);
    }
    //提交商务人员对商家审核内容
    public function submitShopReviewByBusinessPeople() {
        $verifyResult = $this->request->get('verifyresult'); //1表示审核通过， 0表示审核不通过
        $verifyNote = $this->request->get('verifynote');
        $adminUserId = Auth::guard('adminweb')->id();
        $shopReviewId = $this->request->get('shopreviewid');
        if($verifyResult == '1') {
            $data = [
                'firstverifyid' => $adminUserId,
                'firstverifynote' => $verifyNote,
                'firstverifytime' => date('Y-m-d H:i:d'),
                'status' => '1'
            ];
        } else {
            $data = ['status' => ''];
        }
        $result = ShopManagement::editShopReview($shopReviewId, $data);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            if($verifyResult == '1'){

            }
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //提交客服人员对商家审核内容
    public function submitShopReviewByCustomer() {
        $verifyResult = $this->request->get('verifyresult'); //1表示审核通过， 0表示审核不通过
        $verifyNote = $this->request->get('verifynote');
        $adminUserId = Auth::guard('adminweb')->id();
        $shopReviewId = $this->request->get('shopreviewid');
        $cityId = $this->request->get('cityid');
        //获取商家级别
        $shopGrade = $this->request->get('grade');
        if($verifyResult == '1') {
            //审核通过
            $data = [
                'lastverifyid' => $adminUserId,
                'lastverifynote' => $verifyNote,
                'lastverifytime' => date('Y-m-d H:i:d'),
                'status' => '2'
            ];
            $result = ShopManagement::editShopReview($shopReviewId, $data);
            if($result['status'] == 'failed') {
                return $this->responseError($result['message']);
            } else {
                if(empty($shopGrade) || !in_array($shopGrade,array('A级','B级','C级','D级'))){
                    return $this->responseError('请选择正确的级别');
                }
                //将shop_review表数据插入到shop
                $shopReviewResult = ShopManagement::shopReviewDetails($shopReviewId, $cityId);
                if($shopReviewResult['status'] == 'failed') {
                    return $this->responseError($result['message']);
                }
                $shopReviewDetail = $shopReviewResult['data'];
                $newlogo = "upload/shop/" . $shopReviewId."/logo".time();
                $logo  = $shopReviewDetail['logo'];
                $newlogo = (ShopManagement::migrationSingleFile($logo, $newlogo)) ? $newlogo: $logo;

                $photos = $shopReviewDetail['photos'];
                $newphotos = ShopManagement::migrationPhotos($shopReviewId, $photos);
                $newphotos = ($newphotos != '') ? $newphotos: $photos;

                $goodsphotos = $shopReviewDetail['goodsphotos'];
                $newgoodsphotos = ShopManagement::migrationGoodsPhotos($shopReviewId, $goodsphotos);
                $newgoodsphotos = ($newgoodsphotos != '') ? $newgoodsphotos : $goodsphotos;

                $newbankcardphoto = "upload/shop/" .$shopReviewId . '/bankcard' . time();
                $bankcardphoto = $shopReviewDetail['bankcardphoto'];
                $newbankcardphoto = (ShopManagement::migrationSingleFile($bankcardphoto, $newbankcardphoto))?$newbankcardphoto:$bankcardphoto;

                $newlicensephoto = "upload/shop/" .$shopReviewId . "/license" .time();
                $licensephoto = $shopReviewDetail['licensephoto'];
                $newlicensephoto = (ShopManagement::migrationSingleFile($licensephoto, $newlicensephoto))?$newlicensephoto:$licensephoto;

                $newidcardfrontphoto = "upload/shop/" .$shopReviewId . "/idcardfront" . time();
                $idcardfrontphoto = $shopReviewDetail['idcardfrontphoto'];
                $newidcardfrontphoto = (ShopManagement::migrationSingleFile($idcardfrontphoto, $newidcardfrontphoto))?$newidcardfrontphoto:$idcardfrontphoto;

                $newidcardbackphoto = "upload/shop/" .$shopReviewId . '/idcardback' .time();
                $idcardbackphoto = $shopReviewDetail['idcardbackphoto'];
                $newidcardbackphoto = (ShopManagement::migrationSingleFile($idcardbackphoto, $newidcardbackphoto))?$newidcardbackphoto:$idcardbackphoto;

                $shopData = [
                    'code' => $shopReviewDetail['code'],
                    'name' => $shopReviewDetail['name'],
                    'logo' => $newlogo,
                    'firstclassid' => $shopReviewDetail['firstclassid'],
                    'secondclassid' => $shopReviewDetail['secondclassid'],
                    'firstclassname' => $shopReviewDetail['firstclassname'],
                    'secondclassname' => $shopReviewDetail['secondclassname'],
                    'label' => $shopReviewDetail['label'],
                    'maxsales' => $shopReviewDetail['maxsales'],
                    'provinceid' => $shopReviewDetail['provinceid'],
                    'cityid' => $shopReviewDetail['cityid'],
                    'districtid' => $shopReviewDetail['districtid'],
                    'businessareaid' => $shopReviewDetail['businessareaid'],
                    'cityname' => $shopReviewDetail['cityname'],
                    'districtname' => $shopReviewDetail['districtname'],
                    'businessareaname' => $shopReviewDetail['businessareaname'],
                    'longitude' => $shopReviewDetail['longitude'],
                    'latitude' => $shopReviewDetail['latitude'],
                    'address' => $shopReviewDetail['address'],
                    'photos' => $newphotos,
                    'goodsphotos' => $newgoodsphotos,
                    'consumerinfo' => $shopReviewDetail['consumerinfo'],
                    'invoice' => $shopReviewDetail['invoice'],
                    'notpartakegoods' => $shopReviewDetail['notpartakegoods'],
                    'content' => $shopReviewDetail['content'],
                    'description' => $shopReviewDetail['description'],
                    'contactnumber' => $shopReviewDetail['contactnumber'],
                    'smsphone' => $shopReviewDetail['smsphone'],
                    'businesshours' => $shopReviewDetail['businesshours'],
                    'weekdoubleday' => $shopReviewDetail['weekdoubleday'],
                    'buynumber' => $shopReviewDetail['buynumber'],
                    'ordernumber' => 0,
                    'commentnumber'=> 0,
                    'commentscore' => 0.0,
                    'status' => 1,
                    'todayevent' => '0',
                    'nightevent' => '0',
                    'nextevent' => '',
                    'maintainerid' => $shopReviewDetail['maintainerid'],
                    'oldid' => $shopReviewDetail['maintainerid'],
                    'oldmaintainer' => AdminUser::where('id', $shopReviewDetail['maintainerid'])->pluck('realname')->first(),
                    'lastevent' => '',
                    'parentmobile' => $shopReviewDetail['parentmobile'],
                    'parentname' => $shopReviewDetail['parentname'],
                    'childmobile' => '',
                    'idcard' => $shopReviewDetail['idcard'],
                    'cardholder' => $shopReviewDetail['cardholder'],
                    'bankname' => $shopReviewDetail['bankname'],
                    'bankcard' => $shopReviewDetail['bankcard'],
                    'opencardbank'=>$shopReviewDetail['opencardbank'],
                    'bankprovince' => $shopReviewDetail['bankprovince'],
                    'bankcity' => $shopReviewDetail['bankcity'],
                    'bankcardphoto' => $newbankcardphoto,
                    'licensephoto' => $newlicensephoto,
                    'idcardfrontphoto' => $newidcardfrontphoto,
                    'idcardbackphoto' => $newidcardbackphoto,
                    'eventremark'=>$shopReviewDetail['eventremark'],
                    'grade'=>$shopGrade,
                ];
                //添加商家
                $addShopResult = ShopManagement::addShop($shopData);
                if($addShopResult['status'] == 'success') {
                    $shopId = $addShopResult['data']['shopid'];
                    $auth = [
                        $shopId => ['Admin', "Account", "CommentManager", "OrderManager", "CollectMoney", "DoubleCalendar"]
                    ];

                    //添加商家管理人员
                    $addShopUser = ShopManagement::addShopUser($shopReviewDetail['parentname'], $shopReviewDetail['parentmobile'], $auth, $shopId);
                    //添加商家活动日
                    $addShopEvent = ShopManagement::addShopEvent($shopId, $shopReviewDetail['event']);
                    //新增商家签约
                    $addShopContract = ShopManagement::renewShop($shopId, $shopReviewDetail['maintainerid'], $shopReviewDetail['contractstarttime'], $shopReviewDetail['contractendtime']);
                    //审核通过写入shop_check
                    //$addShopStatus = ShopManagement::addShopStatus($shopId, "new", 0, 'customer_check_pass', $verifyNote);
                    $addShopStatus = ShopLog::writeShopLog($shopId, "new", 0, '审核通过', $verifyNote);
                    //添加地推人员
                    if($cityId == 1) {
                        //默认给南昌开放商家地推
                        $addShopSalesman = ShopSalesmanManagement::addShopSalesman($shopId, $cityId, 'common');
                    }
                    //发送首次入住
                    $sendSms = ShopManagement::sendSmsToShopForFirstEnterOrRenew($shopReviewDetail['parentmobile'], $shopReviewDetail['name'], $shopReviewDetail['cardholder'],$shopReviewDetail['bankcard'], 0);
                }
                return $this->responseSuccessMessage($result['message']);
            }
        } else {
            //审核不通过
            $data = [
                'lastverifyid' => $adminUserId,
                'lastverifynote' => $verifyNote,
                'lastverifytime' => date('Y-m-d H:i:d'),
                'status' => '0'
            ];
            $result = ShopManagement::editShopReview($shopReviewId, $data);
            if($result['status'] == 'failed') {
                return $this->responseError($result['message']);
            } else {
                return $this->responseSuccessMessage($result['message']);
            }
        }
    }
    //客服人员删除shopreview记录
    public function deleteShopReviewByCustomer() {
        $cityId = $this->request->get('cityid');
        $shopReviewId = $this->request->get('shopreviewid');
        $result = ShopManagement::delShopReviewByCustomer($shopReviewId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //取消, 开通今日翻倍日
    public function updateShopTodayEvent() {
        $shopId = $this->request->get('shopid');
        //$cityId = $this->request->get('cityid');
        $type = $this->request->get('type');
        if($this->request->has('deductiontype')) {
            $deductionType = $this->request->get('deductiontype');
        } else {
            $deductionType = '0';
        }
        if($this->request->has('deductionnote')) {
            $deductionNote = $this->request->get('deductionnote');
        } else {
            $deductionNote = '';
        }
        $result = ShopManagement::todayDoubleEdit($shopId, $type, $deductionType,$deductionNote);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        //TODO 写入更改状态
        return $this->responseSuccessMessage($result['message']);
    }
    //商家下架列表
    public function shopDownShelfList() {
        $cityId = $this->request->get('cityid');
        $startTime = '';
        $lastTime = '';
        $search = '%';
        $result = ShopManagement::banShopManagement($cityId, $startTime, $lastTime, $search);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId
        ];
        return view('console.shop.shop_offtheshelf', $data);
    }
    //商家状态记录
    public function shopStatusList() {
        $cityId = $this->request->get('cityid');
        if($this->request->has('starttime')) {
            $startTime = $this->request->get('starttime');
        } else {
            $startTime = '';
        }
        if($this->request->has('lasttime')) {
            $lastTime = $this->request->get('lasttime');
        } else {
            $lastTime = '';
        }
        if($this->request->has('search')) {
            $search = $this->request->get('search');
        } else {
            $search = '';
        }
        if($this->request->has('page')) {
            $page = $this->request->get('page');
        } else {
            $page = 1;
        }
        $length = 50;
        $skip = ($page - 1) * $length;
        $totalResult = ShopManagement::getShopStatusTotal($cityId, $startTime, $lastTime, $search);
        if($totalResult['status'] == 'failed') {
            $total = 0;
        } else {
            $total = $totalResult['data'];
        }
        $result = ShopManagement::shopStatusList($cityId, $startTime, $lastTime, $search, $skip, $length);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId,
            'page' => $page,
            'search' => $search,
            'total' => $total,
            'lastpage' => ceil($total/$length),
        ];
        // dd($data);return false;
        return view('console.shop.shop_status_list', $data);

    }
    //商家最后活动日列表续签
    public function shopLastEventList() {
        $cityId = $this->request->get('cityid');
        $startTime = $this->request->get('starttime');
        $lastTime = $this->request->get('lasttime');
        $page = $this->request->get('page');
        $perpage = 2000;
        $result = ShopManagement::shopLastEventList($cityId, $startTime, $lastTime, $perpage);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId,
            'starttime' => $startTime,
            'lasttime' => $lastTime,
        ];
        return view('console.shop.shop_last_event_list', $data);
    }
    //导出商家最后活动日列表
    public function exportShopLastEventList() {
        $cityId = $this->request->get('cityid');
        $startTime = $this->request->get('starttime');
        $lastTime = $this->request->get('lasttime');
        $result = ShopManagement::exportShopLastEventList($cityId, $startTime, $lastTime);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $data = $result['data'];
        $cellData = [['商家代码','商家名称','商务姓名','商务账号','商家状态','合同到期日']];
        foreach($data as $list) {
            $showStatus = ($list->shopstatus==1) ? "在线" : "下架";
            array_push($cellData, [
                'shopcode' => $list->shopcode,
                'shopname' => $list->shopname,
                'realname'=>$list->realname,
                'mobile'=>$list->mobile,
                'status' => $showStatus,
                'lasttime' => $list->lasttime,
            ]);
        }
        $title = '商家续签管理列表';
        Excel::create($title,function($excel) use ($cellData){
            $excel->sheet('商家续签管理列表', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
        return $this->responseSuccessMessage('导出成功');
    }
    //近期无翻贝日的商家
    public function shopWithoutEventList() {
        $cityId = $this->request->get('cityid');
        $length = 10000;
        if($this->request->has('page')) {
            $page = $this->request->get('page');
        } else {
            $page = 1;
        }
        $result = ShopManagement::shopWithoutEventList($cityId, $length, $page);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists'=>$lists,
            'cityid'=>$cityId
        ];
        return view('console.shop.shop_without_event_list', $data);
    }
    //导出近期无翻贝日的商家
    public function exportshopWithoutEventList() {
        $cityId = $this->request->get('cityid');
        //导出excel表格
        $shopsInfo = ShopManagement::exportShopWithoutEventList($cityId);
        if($shopsInfo['status'] == 'failed'){
            return $this->responseError('导出失败');
        }
        $cellData = [['商户代码','商家名称','所在区县','地址','商家最后翻贝日期','维护人']];
        foreach($shopsInfo['data'] as $list) {
           // $showStatus = ($list->status==1) ? "在线" : "下架";
            $newList = [
                'shopcode' => $list['shopcode'],
                'shopname' => $list['shopname'],
                'districtname' => $list['districtname'],
                'address' => $list['shopaddress'],
                'lastevent' => $list['lastevent'],
                'realname'  =>$list['realname']
            ];
            array_push($cellData, $newList);
        }
        $title = '近期无翻倍日商家列表';
        Excel::create($title,function($excel) use ($cellData){
            $excel->sheet('近期无翻倍日商家列表', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
        return $this->responseSuccessMessage('导出成功');
    }
    //修改商家级别
    public function updateShopGrade(){
        $shopId = $this->request->get('shopid');
        $shopGrade = $this->request->get('grade');
        $cityId = $this->request->get('cityid');
        $result = ShopManagement::updateShopGrade($shopId,$shopGrade,$cityId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //修改商家维护人员
    public function updateShopMaintainer() {
        $shopId = $this->request->get('shopid');
        $updateRole = $this->request->get('updaterole');
        if($updateRole == 'new') {
            $maintainerId = $this->request->get('maintainerid');
            $result = ShopManagement::updateShopMaintainerId($shopId, $maintainerId);
        } elseif($updateRole == 'old') {
            $oldMaintainer = $this->request->get('oldmaintainer');
            $result = ShopManagement::updateShopOldMaintainer($shopId, $oldMaintainer);
        } elseif($updateRole == 'shop_review'){//修改待审核和审核不通过的商家中的维护人
            $maintainerId = $this->request->get('maintainerid');
            $result = ShopManagement::updateShopReviewMaintenance($shopId, $maintainerId);
        }else {
            return $this->responseError('参数不对');
        }
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //翻倍日管理
    public function doubledayChoose() {
        $cityId = $this->request->get('cityid');
        if($this->request->has('starttime')) {
            $startTime = $this->request->get('starttime');
            $lastTime = $this->request->get('lasttime');
            $startTime = date('Y-m-d',strtotime($startTime)) . " 00:00:00";
            $lastTime = date('Y-m-d',strtotime($lastTime)) . " 23:59:59";
        } else {
            if($this->request->has('type')) {
                $type = $this->request->get('type');
            } else {
                $type = 'thismonth';
            }
            if($type == 'today') {
                $startTime = date('Y-m-d') . ' 00:00:00';
                $lastTime = date('Y-m-d') . ' 23:59:59';;
            } elseif($type == 'yesterday') {
                $startTime = date('Y-m-d', strtotime("-1day")) . ' 00:00:00';
                $lastTime = date('Y-m-d', strtotime("-1day")) . ' 23:59:59';
            } elseif($type == 'week') {
                $startTime = date("Y-m-d",strtotime("-1 week Monday")) . " 00:00:00";
                $lastTime = date('Y-m-d') . " 23:59:59";
            } elseif($type == 'thismonth') {
                $startTime = date('Y-m') . "-01 00:00:00";
                $lastTime = date('Y-m-d') . " 23:59:59";
            } elseif($type == 'lastmonth') {
                $firstDay = date("Y-m-01");
                $startTime = date('Y-m-01', strtotime($firstDay)-86400) . " 00:00:00";
                $lastTime = date("Y-m-d", strtotime($firstDay)-86400) . " 23:59:59";
            } elseif($type == 'all') {
                $startTime = "2016-07-01 00:00:00";
                $lastTime = date("Y-m-d") . " 23:59:59";
            } else {
                return view('errors.404');
            }
        }
        if($this->request->has('page')) {
            $page = $this->request->get('page');
        } else {
            $page = 1;
        }
        $result = ShopManagement::doubleDayManagement($cityId, $startTime, $lastTime);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId,
            'starttime' => $startTime,
            'lasttime' => $lastTime,
            'lastpage' => 10,
            'page' => $page,
            'search' => ''
        ];
        return view('console.shop.doubleday_choose', $data);
    }
    //翻倍日详情
    public function doubledayDetails() {
        $cityId = $this->request->get('cityid');
        $event = $this->request->get('event');
        $firstClassId = '%';
        $secondClassId = '%';
        $status = '%';
        $search = '%';
        $result = ShopManagement::doubleDayDetails($event, $firstClassId, $secondClassId, $status, $search,$cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = [
            'cityid' => $cityId,
            'event' => $event,
            'lists' => $result['data'],
            'todaytime'=>strtotime(date('Y-m-d',time())),
            'strtotimeevent'=>strtotime($event)
        ];
        return view('console.shop.doubleday_details', $data);
    }
    //导出翻贝日
    public function exportDoubleDay() {
        $cityId = $this->request->get('cityid');
        $event = $this->request->get('event');
        $firstClassId = '%';
        $secondClassId = '%';
        $status = '%';
        $search = '%';
        $result = ShopManagement::exportDoubleDay($event,$cityId);
        if($result['status'] == 'failed') {
            return $this->responseError('导出失败');
        }
        $data = $result['data'];
        $cellData = [
            [
                '序号','一级分类', '二级分类', '商家代码', '门店名称', '开拓人','维护人','商家级别','日期'
            ]
        ];
        foreach($data as $key=>$list){
            $shopId = $list['shopid'];
            $newList = [
                "shopid" => ($key+1),
                "firstclassname" => $list['firstclassname'],
                "secondclassname" => $list['secondclassname'],
                "shopcode" => $list['shopcode'],
                "shopname" => $list['shopname'],
                'oldmaintainer'=>$list['oldmaintainer'],
                'maintainer' => $list['realname'],
                'grade'=>$list['grade'],
                'shopevent'=>$list['shopevent'],
            ];
            array_push($cellData , $newList);
        }
//        $threshold = 3; //超过订单数量
//        foreach($data as $list) {
//            if(strstr($list['oldmaintainer'], '-')) {
//                $maintainer = $list['oldmaintainer'];
//            } else {
//                if($list['realname'] == $list['oldmaintainer']) {
//                    $maintainer = $list['realname'];
//                } else {
//                    $maintainer = $list['realname'] . '-' . $list['oldmaintainer'];
//                }
//            }
//            $shopId = $list['shopid'];
//            $label = ShopManagement::getShopContractCountByShopId($shopId);
//            $orderCount = ShopManagement::getvalidOrderCountByShopId($shopId, $list['firstclassid'], $list['secondclassid']);
//            if($orderCount >= $threshold) {
//                $orderInfo = "是";
//            } else {
//                $orderInfo = "否";
//            }
//            $newList = [
//                "shopid" => $shopId,
//                "shopname" => $list['shopname'],
//                "shopcode" => $list['shopcode'],
//                "firstclassname" => $list['firstclassname'],
//                "secondclassname" => $list['secondclassname'],
//                "todayevent" => $event,
//                "contactnumber" => $list['contactnumber'],
//                'maintainer' => $maintainer,
//                'label' => $label,
//                'orderinfo' => $orderInfo
//            ];
//            array_push($cellData , $newList);
//        }
        $cityName = City::where('id',$cityId)->pluck('name')->first();
        if(!$cityName){
            $cityName = '南昌市';
        }
        $title = $cityName.$event .'翻倍日';
        Excel::create($title,function($excel) use ($cellData){
            $excel->sheet('翻倍日', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
        return $this->responseSuccessMessage('导出成功');
    }
    //夜场管理
    public function nightManage() {
        $cityId = $this->request->get('cityid');
        $startTime = '';
        $lastTime = '';
        $result = ShopManagement::nightEventManagement($cityId, $startTime, $lastTime);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId
        ];
        return view('console.shop.night_manage', $data);
    }
    //修改禁止商家夜场活动
    public function updateShopForbidNightEvent() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $type = $this->request->get('type');
        $result = ShopManagement::updateShopForbidNightEvent($shopId, $cityId, $type);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //夜场详情
    public function nightDetails() {
        return view('console.shop.night_details');
    }
    //商家帮助中心
    public function shopHelp() {
        return view('console.shop.shop_help');
    }
    //反馈管理
    public function shopFeedbackManage() {
        $cityId = $this->request->get('cityid');
        $type = 'shop';
        $result = Common::feedback($type,$cityId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [
            'lists' => $lists,
            'cityid' => $cityId
        ];
        return view('console.shop.shop_feedback_manage', $data);
    }
    //导出商家的反馈列表
    public function shopFeedbackManageExport(){
        $cityId = $this->request->get('cityid');
        $type = $this->request->get('type');
        $result = Common::feedbackManageExport($type,$cityId);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        }
        $data = $result['data'];
        $cellData = [['反馈内容','反馈时间','状态']];
        foreach($data as $list) {
            array_push($cellData, [
                'content'=>$list['content'],
                'created_at'=>$list['created_at'],
                'status'=>$list['status'] == 1?'已处理':'未处理',
            ]);
        }
        $title = '商家反馈管理列表';
        Excel::create($title,function($excel) use ($cellData){
            $excel->sheet('商家反馈管理列表', function($sheet) use ($cellData){
                $sheet->rows($cellData);
            });
        })->export('xls');
        return $this->responseSuccessMessage('导出成功');
    }
    //反馈详情
    public function shopFeedbackDetailed() {
        $cityId = $this->request->get('cityid');
        $feedbackId = $this->request->get('feedbackid');
        $result = Common::getFeedbackDetail($feedbackId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;
        return view('console.shop.shop_feedback_detailed', $data);
    }
    //编辑反馈
    public function editShopFeedback() {
        $cityId = $this->request->get('cityid');
        $feedbackId = $this->request->get('feedbackid');
        $status = $this->request->get('status');
        $note = $this->request->get('note');
        $result = Common::editFeedback($feedbackId, $status, $note);
        if($result['status'] == 'failed') {
            return $this->responseError($result['message']);
        } else {
            return $this->responseSuccessMessage($result['message']);
        }
    }
    //消息管理
    public function shopMessageManage() {
        $result = ['status'=>'success', 'data'=>[]];
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        return view('console.shop.shop_message_manage', ['lists'=>$lists]);
    }
    //新增/修改消息内容
    public function shopMessageCheck() {
        return view('console.shop.shop_message_check');
    }
    //商家入驻
    public function shopJoinIn() {
        if($this->request->has('starttime')) {
            $startTime = $this->request->get('starttime');
            $lastTIme = $this->request->get('lasttime');
        } else {
            $startTime = "";
            $lastTIme = "";
        }
        if($this->request->has('page')) {
            $page = $this->request->get('page');
        } else {
            $page = 1;
        }
        $cityId = $this->request->get('cityid');
        $result = Common::shopJoinIn($cityId, $startTime, $lastTIme, $page);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $lists = $result['data'];
        $data = [ 'lists'=>$lists ];
        return view('console.shop.shop_joinin', $data);
    }
    //商家二维码管理
    public function shopCodeManage() {
        return view('console.shop.shop_code_manage');
    }
    //日志
    public function dailyRecord() {
        $cityId = $this->request->get('cityid');
        $shopId = $this->request->get('shopid');
        $result = ShopManagement::getShopStatusDetailByShopId($shopId);
        if($result['status'] == 'failed') {
            return view('errors.404');
        }
        $data = $result['data'];
        $data['cityid'] = $cityId;

        return view('console.shop.daily_record', $data);
    }
    //test
    public function test() {
        $photos = [
            "",
            "",
            "",
            "",
            "",
        ];
        $goodsPhotos = [
            [
                "name"=>'测试商品',
                'description'=>'测试商品',
                "url" => ''
            ],
            [
                "name"=>'',
                'description'=>'',
                "url" => ''
            ],
        ];
        $code = "";
        $photosJson = json_encode($photos);
        $goodsPhotosJson = json_encode($goodsPhotos);
        $shops = Shop::where('code', $code)->get();
        foreach($shops as $shop) {
            $shop->photos = $photosJson;
            $shop->goodsphotos = $goodsPhotosJson;
            $shop->save();
        }
    }
}